package me.leiusual.sharing.ui.base

import android.Manifest
import android.content.Intent
import dagger.android.support.DaggerAppCompatActivity
import pub.devrel.easypermissions.AfterPermissionGranted
import pub.devrel.easypermissions.AppSettingsDialog
import pub.devrel.easypermissions.EasyPermissions
import timber.log.Timber

/**
 * Create by leiusual on 2018/7/15
 */
abstract class AbstractActivity : DaggerAppCompatActivity(), EasyPermissions.PermissionCallbacks {

  companion object {
    private const val REQUEST_PERMISSIONS = 1
  }

  override fun onStart() {
    super.onStart()

    // 请求权限
    requestPermissions()
  }

  override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)

    // 从设置页面返回了
    if (requestCode == AppSettingsDialog.DEFAULT_SETTINGS_REQ_CODE) {
      Timber.v("Do something after user returned from app settings screen")
    }
  }

  override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults)

    // 转发结果到EasyPermissions
    EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this)
  }

  override fun onPermissionsGranted(requestCode: Int, perms: MutableList<String>) {
    Timber.v("onPermissionsGranted requestCode = %s, perms = %s", requestCode, perms)
  }

  override fun onPermissionsDenied(requestCode: Int, perms: MutableList<String>) {
    Timber.v("onPermissionsDenied requestCode = %s, perms = %s", requestCode, perms)

    if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
      Timber.v("user checked \"NEVER ASK AGAIN.\"")

      // 提示用户在应用程序设置中启用权限
      AppSettingsDialog.Builder(this)
          .setTitle("提醒")
          .setRationale("请在设置中打开权限")
          .build()
          .show()
    }
  }

  /**
   * 请求权限
   */
  @AfterPermissionGranted(REQUEST_PERMISSIONS)
  private fun requestPermissions() {
    // 权限列表
    val perms = arrayOf(
        Manifest.permission.READ_PHONE_STATE,
        Manifest.permission.ACCESS_NETWORK_STATE,
        Manifest.permission.ACCESS_WIFI_STATE,
        Manifest.permission.WRITE_EXTERNAL_STORAGE,
        Manifest.permission.READ_EXTERNAL_STORAGE,
        Manifest.permission.CAMERA
    )
    if (EasyPermissions.hasPermissions(this, *perms)) {
      // 已经有权限了
      Timber.v("hasPermissions")
    } else {
      // 没有权限就立即发起请求
      Timber.v("requestPermissions")
      EasyPermissions.requestPermissions(this, "扫描二维码需要打开相机等权限", REQUEST_PERMISSIONS, *perms)
    }
  }
}